class BudgetsController < ApplicationController
  before_filter :login_required, :only => [ :new, :create, :index, :show ]

  def new
    @budget = Budget.new
  end
  
  def index
    @my_total = 0
    @bills_total = 0
    
    @budgets = Budget.find(:all, :conditions => ["user_id = ?", @current_user.id]).each do |budget|
      #Add the entries to get total
      @my_total += budget.budget_amount
      
      #Only add the entries to tagged "Bills"
      if budget.budget_type == "Bills"
        @bills_total += budget.budget_amount
      end
    end  
  end
  
  def create
    @budget = @current_user.budgets.build(params[:budget])
    @budget.entry_date = Time.now
    if @budget.save
      flash[:notice] = "Entry submission succeeded"
      redirect_to budget_path(@budget)
    else
      render :action => 'new'
    end
  end
  
  def update
    @budget = Budget.find(params[:id])
    if @budget.update_attributes(params[:budget])
      flash[:notice] = "Entry submission updated"
      redirect_to budget_path(@budget)
    else
      render :action => 'new'
    end
  end
  
  def show
    @budget = Budget.find(params[:id])
  end
  
  def edit
    @budget = Budget.find(params[:id])
  end
  
  def destroy
    @budget = Budget.find(params[:id])
    @budget.destroy
    redirect_to budgets_path
  end
  
  def calculate_total
    @budgets = Budget.find :all
    @myTotal = 0
    
    @budgets.each do |budget|
      @myTotal += budget.budget_amount
    end
    
    return @myTotal
  end
end
